package smartbooks.restrictDocuments;

import java.awt.Toolkit;
import javax.swing.text.AttributeSet;
import javax.swing.text.BadLocationException;
import javax.swing.text.PlainDocument;

/**
 *
 * @author Ankit
 */
public class JTextFieldMaxLimitDocument extends PlainDocument {
    private final int limit;
    
    /**
     * This is a constructor to define the max length of the component
     * @param limit
     */
    public JTextFieldMaxLimitDocument(int limit) {
        super();
        this.limit = limit;
    }

    @Override
    public void insertString(int offset, String str, AttributeSet attr) throws BadLocationException {
        if (null==str)
            return;

        if ((getLength() + str.length()) <= limit) {
            super.insertString(offset, str, attr);
        } else {
            Toolkit.getDefaultToolkit().beep();
        }
    }
}